package models.dao;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import models.Aluno;

public class DAOAluno implements DAO<Aluno>{

	@Override
	public void inserir(Aluno a) {
		try{
			String inserir = "insert into aluno(email, id) values(?, ?)";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(inserir);
			//Connection connection = DB.getConnection().prepareStatement(inserir);
			
			statement.setString(1, a.email);
			statement.setInt(2, a.id);
			
			statement.executeUpdate();
			
		}catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
			//Connection.close();
		}
		
	}

	@Override
	public void atualizar(Aluno a) {
		try{
			String atualizar = "update alunos set email = ? where id = ?";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(atualizar);
			
			statement.setString(1, a.email);
			statement.setInt(2, a.id);
			
			statement.executeUpdate();
			
		}catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
		}

	}

	@Override
	public void deletar(Aluno a) {
		try{
			String deletar = "delete from aluno where id = ?";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(deletar);
			
			statement.setInt(1, a.id);
			
			statement.executeUpdate();
			 
		}catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
			
		}
		
	}

	@Override
	public List<Aluno> listar() {
		List<Aluno> aluno = new ArrayList<Aluno>();		
		
		try{
			String listar = "select * from Aluno";
			PreparedStatement statement = DAOConexao.getConnection().prepareStatement(listar);
			ResultSet result = statement.executeQuery();
			
			while(result.next()){
				Aluno a = new Aluno();
				
				a.email = result.getString(1);
				a.id = result.getInt(2);
				
				aluno.add(a);
			}
			
		} catch(SQLException e){
			e.printStackTrace();
			
		}finally{
			DAOConexao.closeConnection();
		}
		
		return aluno;
	}
	
}
